/* Copyright (C) 2011  Chris Mueller <ruunhb@googlemail.com>
 *
 * This file is part of the Liquid Programming Language
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "context.h"
#include "scanner.h"
#include <glib/gstring.h>
#include <glib/goption.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

static gboolean quiet = FALSE;
static gchar**	args = 0;

static GOptionEntry options[] = {
	{"quiet", 'q', 0, G_OPTION_ARG_NONE, &quiet, "Dont show corresponding token strings", 0},
	{G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_STRING_ARRAY, &args, 0, 0},
	{ 0 }
};


int main(int argc, char** argv)
{
	char buffer[128];
	FILE* file = 0;
        GError* error = 0;
	GString* text = g_string_sized_new(12);
	GOptionContext* opt = g_option_context_new("FILE");

	g_option_context_add_main_entries(opt, options, "Options");
	g_option_context_set_summary(opt, "lq-tokenizer show the generated token stream generated by the internal scanner");

        if(!g_option_context_parse(opt, &argc, &argv, &error)) {
		g_printerr("error: %s\n", error->message);
		return EXIT_FAILURE;
	}

	if(!args || !(file = fopen(*args, "r"))) {
		file = stdin;
	}

	while(!feof(file) && (fgets(buffer, sizeof(buffer), file) != 0)) {
		g_string_append(text, buffer);
		memset(buffer, 0, sizeof(buffer));
	}

	lq_scanner_initialize();
	struct LqContext* context = lq_context_new(text->str, "tokenizer");
	struct LqToken token;

	do {
		token = lq_scanner_next(context);

                printf(" %s", lq_tok_to_string(token.value));

		if(token.value == LQ_TOKEN_NEWLINE)
			printf("\n");

		if(token.text != 0) {
                        if(!quiet)
			        printf("<%s>", token.text);

                        g_free(token.text);
		}

	} while(token.value != LQ_TOKEN_EOF);

	printf("\n");

	lq_context_free(context);

	return EXIT_SUCCESS;
}
